package com.falcon.core.service;

import com.falcon.core.domain.AbsPageQuery;
import com.falcon.core.domain.BasePO;
import com.falcon.core.domain.BasePager;
import com.falcon.core.domain.BaseRequest;
import com.falcon.core.utils.BeanUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swan.mybatis.condition.SelectOption;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author zongf
 * @date 2025-02-17
 **/
public abstract class AbsBaseService<E extends BasePO> implements IBaseService<E> {

    private Class<E> entityClass;

    public AbsBaseService() {
        Type genericSuperclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        entityClass =  (Class<E>) parameterizedType.getActualTypeArguments()[0];
    }

    @Override
    public Long save(BaseRequest request) {
        E e = BeanUtils.copyProperties(request, entityClass);
        getMapper().insertNotNull(e);
        return e.getId();
    }

    @Override
    public Boolean update(Long id, BaseRequest request) {
        E e = BeanUtils.copyProperties(request, entityClass);
        e.setId(id);
        return getMapper().updateNotNull(e);
    }

    @Override
    public Boolean deleteById(Long id) {
        return getMapper().deleteById(id);
    }

    @Override
    public E queryById(Long id) {
        return getMapper().selectById(id);
    }

    @Override
    public List<E> queryList(AbsPageQuery request) {
        return getMapper().selectList(request.toCondition(), SelectOption.newInstance().desc(BasePO.Fields.id));
    }

    @Override
    public BasePager<E> queryPager(AbsPageQuery request) {
        PageInfo<E> pageInfo = PageHelper.startPage(request.getPage(), request.getPageSize())
                .doSelectPageInfo(() -> getMapper().selectList(request.toCondition(), SelectOption.newInstance().desc(BasePO.Fields.id)));

        return BeanUtils.toPager(pageInfo);    }

    @Override
    public int batchDelete(List<Long> ids) {
        return getMapper().deleteByIds(ids);
    }

}
